/*
 * @Author: 彭林
 * @Date: 2021-05-14 18:04:47
 * @LastEditTime: 2021-07-14 18:02:13
 * @LastEditors: 彭林
 * @Description:
 * @FilePath: /saas-app/app/service/card.go
 */
package service

import (
	"errors"
	"saas-app/app/dao"
	"saas-app/app/define"
	"unicode/utf8"

	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
)

type CardRepository interface {
	GetCardList(campus_id int, paging *define.PagingParams) (cardList gdb.Result, total int)
	UpdateCard(card_id uint, data g.MapStrAny) bool
	CreateCard(card *define.CardRequest) error
	IsExist(campus_id uint, card_type string) bool
}

type card struct{}

func CardService() CardRepository {
	return &card{}
}

// 学员卡列表
func (c card) GetCardList(campus_id int, paging *define.PagingParams) (cardList gdb.Result, total int) {

	db := dao.Card.Where("campus_id = ?", campus_id)

	if paging.Page > 0 && paging.Limit > 0 {

		total, _ = db.FindCount()

		db = db.Offset((paging.Page - 1) * paging.Limit).Limit(paging.Limit)

	}

	cardList, err := db.FindAll()

	if err != nil {
		panic(err)
	}

	return cardList, total
}

// 更新学员卡
func (c card) UpdateCard(card_id uint, data g.MapStrAny) bool {

	if card_id <= 0 {
		panic("参数错误")
	}

	if data["card_name"] != nil && utf8.RuneCountInString(data["card_name"].(string)) > 20 {
		panic("参数错误 card_name")
	}

	if data["card_name"] == nil {
		panic("参数错误 card_name")
	}

	if data["remark"] != nil && utf8.RuneCountInString(data["remark"].(string)) > 100 {
		panic("参数错误 remark")
	}

	_, err := dao.Card.Where("id = ?", card_id).Update(data)

	if err != nil {
		panic(err)
	}

	return err == nil
}

// 创建学员卡
func (c card) CreateCard(card *define.CardRequest) error {

	if isExist := CardService().IsExist(card.CampusId, card.CardType); isExist {
		return errors.New("该类学员卡已存在")
	} else {
		_, err := dao.Card.Save(card)
		return err
	}
}

// 判断当前学校是否有改类型的学员卡
func (c card) IsExist(campus_id uint, card_type string) bool {
	mcardlist, err := dao.Card.Where("campus_id = ?", campus_id).Where("card_type = ?", card_type).FindAll()
	if len(mcardlist) > 0 && err == nil {
		return true
	}
	return false
}
